package com.johnsoncs.gio.alc;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class SearchableActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.instructions);
        
    }

    @Override
    public void onNewIntent(Intent intent) {
        final String action = intent.getAction();
        if (Intent.ACTION_SEARCH.equals(action)) {
            setContentView(R.layout.search);
            String query = intent.getStringExtra(SearchManager.QUERY);
            search(query);

        }
    }
    
    private void search(String query) {
        
        final ListView lv = (ListView)super.findViewById(R.id.ListView01);
        
        SearchYouTubeTask sytt = new SearchYouTubeTask(lv);
        sytt.execute(query);
        
        
        
    }
    private class SearchResultsAdapter extends BaseAdapter {

        private List<SearchResultItem> results;
        LayoutInflater inflater = (LayoutInflater)SearchableActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        public SearchResultsAdapter(List<SearchResultItem> results) {
            this.results = results;
        }
        public int getCount() {
            return results.size();
        }

        public Object getItem(int position) {
            return results.get(position);
        }

        public long getItemId(int position) {
            return (int)position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            
            SearchResultItem item = results.get(position);
            /*final RelativeLayout rl = (RelativeLayout)inflater.inflate(R.layout.searchresultview, null); //parent, false);
            
            //rl.setClickable(true);
            TextView label = (TextView)rl.findViewById(R.id.label);
            label.setText(item.getTitle());*/
            //label.setClickable(false);
            //label.setFocusable(false);
            
            /*
            
            ImageView thumbnail = (ImageView)v.findViewById(R.id.thumbnail);
            
            
            if(item.getThumbnailUrl() != null) {
                try {
                    URL newurl = new URL(item.getThumbnailUrl()); 
                    thumbnail.setImageBitmap(BitmapFactory.decodeStream(newurl.openConnection() .getInputStream()));
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }*/
            
            TextView v = new TextView(SearchableActivity.this);
            v.setText(item.getTitle() + "\n\nRating: " + rating(item.getRating()) + "\n");
            v.setHapticFeedbackEnabled(true);
            v.setWidth(parent.getWidth());
            //v.setMinHeight(20);
            
            return v;
        }
        
    }
    private static String rating(int v) {
        if(v == -1) {
            return "Not rated";
        }
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < v; i++) {
            sb.append("* ");
        }
        return sb.toString();
    }
    
    
    private class SearchResultItem {
        private String id;
        private String title;
        private String url;
        private String thumbnailUrl;
        private int rating = -1;
        
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getTitle() {
            return title;
        }
        public void setTitle(String title) {
            this.title = title;
        }
        public String getUrl() {
            return url;
        }
        public void setUrl(String url) {
            this.url = url;
        }
        public String getThumbnailUrl() {
            return thumbnailUrl;
        }
        public void setThumbnailUrl(String thumbnailUrl) {
            this.thumbnailUrl = thumbnailUrl;
        }
        public void setRating(int rating) {
            this.rating = rating;
        }
        public int getRating() {
            return rating;
        }
        
        public String toString() {
            return title + "\n" + rating(rating);
        }
        
    }
    private void playVideo(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(intent);
    }
    private void shareVideo(SearchResultItem item) {
        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.setType("text/plain");
        sendIntent.putExtra(Intent.EXTRA_TEXT, item.getUrl());
        Intent chooser = Intent.createChooser(sendIntent, "Share via...");
        startActivity(chooser);
    }
    private class SearchYouTubeTask extends AsyncTask<String, Void, List<SearchResultItem>> {
        private ListView lv;

        public SearchYouTubeTask(ListView lv) {

            this.lv = lv;
        }

        protected List<SearchResultItem> doInBackground(String... params) {

            
            List<SearchResultItem> results = new ArrayList<SearchableActivity.SearchResultItem>();

            try {
                String query = "http://gdata.youtube.com/feeds/api/videos?v=2&caption&format=1,6&q=" + params[0];

                URL url = new URL(query);


                HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

                int respCd = httpConnection.getResponseCode();

                if (respCd == HttpURLConnection.HTTP_OK) {
                    InputStream in = httpConnection.getInputStream();

                    DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = fac.newDocumentBuilder();

                    Document doc = db.parse(in);
                    Element root = doc.getDocumentElement();

                    NodeList nodes = root.getElementsByTagName("entry");
                    if (nodes != null && nodes.getLength() > 0) {
                        for (int i = 0; i < nodes.getLength(); i++) {
                            Element entry = (Element) nodes.item(i);
                            Element title = (Element) entry.getElementsByTagName("title").item(0);
                            Element groupElement = (Element) entry.getElementsByTagName("media:group").item(0);
                            
                            NodeList contentNodes =  groupElement.getElementsByTagName("media:content");
                            Element videoUrlElement = null;
                            for(int j = 0; j < contentNodes.getLength(); j++) {
                                Element temp =(Element)contentNodes.item(j);
                                String tempUrl = temp.getAttribute("url");
                                if(tempUrl != null && tempUrl.toLowerCase().startsWith("http")) {
                                    videoUrlElement = temp;
                                    break;
                                }
                            }
                            
                            NodeList thumbnailNodes = groupElement.getElementsByTagName("media:thumbnail");
                            Element thumbnailElement = null;
                            for(int j = 0; j < thumbnailNodes.getLength(); j++) {
                                Element temp = (Element)thumbnailNodes.item(j);
                                if("default".equals(temp.getAttribute("yt:name"))) {
                                    thumbnailElement = temp;
                                    break;
                                }
                            }
                            
                            NodeList ratings = entry.getElementsByTagName("gd:rating");
                            Element ratingElement = ratings.getLength() > 0 ? (Element)ratings.item(0) : null;
                            
                            if(videoUrlElement != null) {
                                String titleStr = title.getFirstChild().getNodeValue();
                                String videoUrl = videoUrlElement.getAttribute("url");
                                SearchResultItem item = new SearchResultItem();
                                item.setTitle(titleStr);
                                item.setUrl(videoUrl);
                                if(thumbnailElement != null) {
                                    item.setThumbnailUrl(thumbnailElement.getAttribute("url"));
                                }
                                if(ratingElement != null) {
                                    try {
                                        int rating = (int)Double.parseDouble(ratingElement.getAttribute("average"));
                                        item.setRating(rating);
                                    } catch(Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                                results.add(item);
                            }
                        }
                    }
                    
                    
                }
            } catch (Exception e) {
                e.printStackTrace();
            } 

            return results;
        }
        protected void onPostExecute(final List<SearchResultItem> result) {
            SearchResultsAdapter sra = new SearchResultsAdapter(result);
            lv.setAdapter(sra);
            
            lv.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    
                    SearchResultItem item = result.get(position);
                    playVideo(item.getUrl());
                }
            });
            
            lv.setOnItemLongClickListener(new OnItemLongClickListener() {
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    SearchResultItem item = result.get(position);
                    shareVideo(item);
                    return true;
                }
                
            });
            
            lv.scheduleLayoutAnimation();
        }
        
        
    }
    

}
